<script setup lang="ts">
import type {
  FormInstance,
  FormRules,
  UploadFile,
  UploadFiles,
  UploadProps
} from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

import { useUserStore } from '@/store/modules/user'
import { storeToRefs } from 'pinia'
const userStore = useUserStore()
const { certificatesTypeData } = storeToRefs(userStore)

const userInfoRef = ref<FormInstance>()
const uploadRef = ref()
const userInfoForm = reactive({
  name: '',
  certificatesType: '',
  certificatesNo: '',
  certificatesUrl: ''
})
const ValidityName = (rule: any, value: any, cb: any) => {
  const reg =
    /^[\u00B7\u3007\u3400-\u4DBF\u4E00-\u9FFF\uE000-\uF8FF\uD840-\uD8C0\uDC00-\uDFFF\uF900-\uFAFF]+$/u
  if (reg.test(value)) {
    cb()
  } else {
    cb(new Error('请输入正确的中文名字'))
  }
}
const ValidityType = (rule: any, value: any, cb: any) => {
  if (value == '10' || value == '20') {
    cb()
  } else {
    cb(new Error('请选择证件的类型'))
  }
}
const ValidityNo = (rule: any, value: any, cb: any) => {
  const _IDRe18 =
    /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  const _IDre15 =
    /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/

  // 户口本
  const hkb = /^\d{9}$/
  // 校验身份证：
  if (_IDRe18.test(value) || _IDre15.test(value) || hkb.test(value)) {
    cb()
  } else {
    cb(new Error('请输入正确的身份证号或者户口本号码'))
  }
}
const ValidityUrl = (rule: any, value: any, cb: any) => {
  if (value.length) {
    cb()
  } else {
    cb(new Error('请上传图片！'))
  }
}
const formRules = reactive<FormRules<typeof userInfoForm>>({
  name: [
    {
      required: true,
      validator: ValidityName,
      trigger: 'change'
    }
  ],
  certificatesType: [
    {
      required: true,
      validator: ValidityType,
      trigger: 'change'
    }
  ],
  certificatesNo: [
    {
      required: true,
      validator: ValidityNo
    }
  ],
  certificatesUrl: [
    {
      required: true,
      validator: ValidityUrl
    }
  ]
})
// 图片上传
const dialogVisible = ref(false)

const onExceedHandle = () => {
  ElMessage.warning('只能上传一张图片！')
}
const onSuccessHandle = (response: any) => {
  if (response.code == 200) {
    userInfoForm.certificatesUrl = response.data
    userInfoRef.value?.clearValidate('certificatesUrl')
  } else {
    ElMessage.error('无法获取上传图片的地址！')
  }
}
const onRemoveHandle = () => {
  userInfoForm.certificatesUrl = ''
}
// 预览
const onPreviewHandle: UploadProps['onPreview'] = () => {
  dialogVisible.value = true
}
// 重置按钮
const resetBtnClick = () => {
  // userInfoRef.value?.resetFields()
  uploadRef.value?.clearFiles()
  Object.assign(userInfoForm, {
    name: '',
    certificatesType: '',
    certificatesNo: '',
    certificatesUrl: ''
  })
}
// 提交
const submitBtnClick = async () => {
  const res = await userInfoRef.value?.validate()
  if (res) {
    const config = {
      name: userInfoForm.name,
      certificatesNo: userInfoForm.certificatesNo,
      certificatesType: userInfoForm.certificatesType,
      certificatesUrl: userInfoForm.certificatesUrl
    }
    userStore.fetchUserAuthAction({ ...config })
  } else {
    ElMessage.error('认证失败！')
  }
}
// 证件类型
onMounted(() => {
  userStore.fetchGetReqCertificatesType()
})
</script>
<template>
  <div class="no-certificate">
    <div class="notice-box">
      <el-icon class="icon" size="18">
        <Warning />
      </el-icon>
      完成实名认证后才能添加就诊人，正常进行挂号，为了不影响后续步骤，建议提前实名认证。
    </div>

    <div class="form-box">
      <el-form
        :model="userInfoForm"
        label-position="right"
        label-width="100"
        :rules="formRules"
        class="form-cert"
        ref="userInfoRef"
      >
        <el-form-item label="姓名：" prop="name">
          <el-input v-model="userInfoForm.name" placeholder="请输入姓名">
          </el-input>
        </el-form-item>
        <el-form-item label="证件类型：" prop="certificatesType">
          <el-select
            v-model="userInfoForm.certificatesType"
            placeholder="请选择证件的类型"
          >
            <template v-for="item in certificatesTypeData" :key="item.id">
              <el-option :label="item.name" :value="item.value"> </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码：" prop="certificatesNo">
          <el-input
            v-model="userInfoForm.certificatesNo"
            placeholder="请输入证件号码"
          ></el-input>
        </el-form-item>
        <el-form-item label="上传证件：" prop="certificatesUrl">
          <el-upload
            ref="uploadRef"
            list-type="picture-card"
            action="http://syt.atguigu.cn/api/oss/file/fileUpload?fileHost=userAuah"
            :limit="1"
            :on-exceed="onExceedHandle"
            :on-success="onSuccessHandle"
            :on-preview="onPreviewHandle"
            :on-remove="onRemoveHandle"
          >
            <img
              class="default-img"
              src="../../../../assets/images/auth_example.png"
              alt=""
            />
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img
              w-full
              v-if="userInfoForm.certificatesUrl"
              style="width: 100%; height: 100%"
              :src="userInfoForm.certificatesUrl"
              alt="Preview Image"
            />
          </el-dialog>
        </el-form-item>
        <el-form-item>
          <div class="item-btn">
            <el-button type="primary" class="form-btn" @click="submitBtnClick">
              提交
            </el-button>
            <el-button type="primary" class="form-btn" @click="resetBtnClick">
              重置
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<style scoped lang="less">
.no-certificate {
  .notice-box {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #999;
    margin: 20px 0;
    font-size: 14px;
    font-weight: normal;

    .icon {
      margin: 0 7px;
    }
  }

  .form-box {
    width: 60%;
    margin: 0 auto;

    .form-cert {
      .el-select {
        width: 100%;
      }
      .default-img {
        width: 100%;
      }
      .item-btn {
        display: flex;
        width: 100%;
        justify-content: start;
        margin: 30px 0;
      }

      .form-btn {
        justify-content: center;
        align-items: center;
        background-color: #4490f1;
        box-shadow: 0 10px 20px - 10px rgba(73, 144, 241, 0.5);
        border-radius: 4px;
        height: 44px;
        color: #fff;
        font-size: 16px;
        font-weight: 500;
        transition: all 0.2s ease;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        cursor: pointer;
        width: 140px;
        margin-right: 30px;
      }
    }
  }
}
</style>
